home *** CD-ROM | disk | FTP | other *** search
- Path: mail2news.demon.co.uk!genesis.demon.co.uk
- From: Lawrence Kirby <fred@genesis.demon.co.uk>
- Newsgroups: comp.lang.c,comp.unix.programmer
- Subject: Re: Q: '\n' character
- Date: Wed, 03 Apr 96 01:01:59 GMT
- Organization: none
- Message-ID: <828493319snz@genesis.demon.co.uk>
- References: <31616F63.481D@lava.weeg.uiowa.edu> <4jrvv3$ask@aimnet.aimnet.com>
- Reply-To: fred@genesis.demon.co.uk
- X-NNTP-Posting-Host: genesis.demon.co.uk
- X-Newsreader: Demon Internet Simple News v1.27
- X-Mail2News-Path: genesis.demon.co.uk
-
- In article <4jrvv3$ask@aimnet.aimnet.com>
- jmcneill@aimnet.com "Jonathan S. McNeill" writes:
-
- >In article <31616F63.481D@lava.weeg.uiowa.edu>,
- >Artur Wojdat <awojdat@lava.weeg.uiowa.edu> wrote:
- >
- >> Is there a function or some sort of way that I could remove '\n'
- >>charecter form the end of the string. I'm reading from two files, want to
- >>form one line of text and then have it printed out to stdout. I use fgets to
- >>read from the file and I noticed that it appends newline char at the end.
-
- The newline character is in the input stream, fgets() simply doesn't
- discard it like gets() does.
-
- >/*
- > * loop through characters until newline or end of file
- > */
- >while ( (ch = getc(stream)) != '\n' && ch != EOF ) {
- >
- > sprintf(buffer, "%s%c", buffer, ch);
-
- This is truely horrific. You can't read and write to the same object with
- sprintf - the result is undefined behaviour. %s requires that you pass
- as the corresponding argument a pointer to a properly null character
- terminated string. There is no indication that buffer holds such a thing
- here.
-
- >}
- >
- >/*
- > * add a trailing nul character so that you can use string functions
- > */
- >sprintf(buffer, "%s\0");
-
- As far as a string is concerned "%s\0" is no different from "%s". There
- is an extra null character in there but a string always terminates at the
- first one so sprintf never sees the 2nd one. Also there's no argument
- corresponding to %s.
-
- There is a simple trick to remove any trailing newline character in a string
- typically written by fgets(), say into buffer, and that is:
-
- strtok(buffer, "\n");
-
- --
- -----------------------------------------
- Lawrence Kirby | fred@genesis.demon.co.uk
- Wilts, England | 70734.126@compuserve.com
- -----------------------------------------
-